<template>
  <div class="record-wrapper">
    <div class="container">
      <div class="page-title">
        职途卡申请
      </div>
      <el-scrollbar class="scrollbar">
        <div class="form-container">
          <el-form
            class="form"
            ref="form"
            :model="form"
            :rules="rules"
            size="small"
            label-width="126px"
            label-suffix="："
          >
            <el-form-item label="职途卡类型" prop="applyType">
              <el-select
                class="select"
                v-model="form.applyType"
                placeholder="请选择职途卡类型"
              >
                <el-option
                  v-for="item in projectTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="showQrCodeExpireTime"
              label="二维码有效期至"
              prop="codeExpireTime"
            >
              <el-date-picker
                class="select"
                value-format="yyyy-MM-dd"
                v-model="form.codeExpireTime"
                type="date"
                placeholder="请选择日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              v-if="showQrCodeExpireTime"
              label="职途卡密码"
              prop="codeKey"
            >
              <el-input
                placeholder="请填写职途卡密码（选填）"
                v-model="form.codeKey"
              ></el-input>
            </el-form-item>
            <el-form-item label="职途卡用途" prop="isTest">
              <el-select
                class="select"
                v-model="form.isTest"
                placeholder="请选择职途卡是否用于内部测试"
              >
                <el-option
                  v-for="item in isTestOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="showCardSource" label="库存">
              <span>{{ stockNum }} 张</span>
            </el-form-item>
            <el-form-item v label="申请张数" prop="applyNum">
              <el-input
                placeholder="请填写申请张数"
                v-model="form.applyNum"
                @input="checkIfNum"
              ></el-input>
            </el-form-item>
            <el-form-item label="权益有效期至" prop="expireTime">
              <el-date-picker
                class="select"
                value-format="yyyy-MM-dd"
                v-model="form.expireTime"
                type="date"
                placeholder="请选择有效期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="申请人" prop="auditAdminName">
              <el-input
                placeholder="请选择申请人"
                v-model="form.auditAdminName"
                @focus="handleFocusInput"
              ></el-input>
            </el-form-item>
            <el-form-item label="申请部门" prop="department">
              <el-input
                disabled
                placeholder="选中申请人后申请部门自动填写"
                v-model="form.department"
              ></el-input>
            </el-form-item>
            <el-form-item label="项目应用方" prop="cardType">
              <el-cascader
                class="select"
                v-model="form.cardType"
                :options="appList"
                placeholder="请选择项目应用方"
                @change="handleChangeCardType"
              ></el-cascader>
            </el-form-item>
            <el-form-item v-if="form.list.length" label="申请权益" prop="list">
              <el-tag
                v-for="(item, index) in form.list"
                :key="index"
                type="info"
              >
                {{ item.rightName }}
              </el-tag>
            </el-form-item>
            <el-form-item label="申请理由" prop="applyReason">
              <el-input
                placeholder="请填写申请理由"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 4 }"
                v-model="form.applyReason"
              ></el-input>
            </el-form-item>
            <el-form-item label="单价" prop="cost">
              <el-input placeholder="请填写单价" v-model="form.cost">
                <template slot="append">元</template></el-input
              >
            </el-form-item>
            <el-form-item label="审核人" prop="auditObj">
              <el-select
                class="select"
                v-model="form.auditObj"
                value-key="auditAdminId"
                placeholder="请选择审核人"
              >
                <el-option
                  v-for="item in auditerList"
                  :key="item.auditAdminId"
                  :label="item.auditAdminName"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <template v-if="form.applyType == 1">
              <el-form-item label="收件人姓名" prop="receiverName">
                <el-input
                  placeholder="请填写收件人姓名"
                  v-model="form.receiverName"
                ></el-input>
              </el-form-item>
              <el-form-item label="收件人电话" prop="receiverPhone">
                <el-input
                  placeholder="请填写收件人电话"
                  v-model="form.receiverPhone"
                ></el-input>
              </el-form-item>
              <el-form-item label="收件地址" prop="receiverAddress">
                <el-input
                  placeholder="请填写详细地址（省、市、区、街道、....）"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 4 }"
                  v-model="form.receiverAddress"
                ></el-input>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="operation">
          <el-button
            class="btn"
            type="primary"
            v-loading="loading"
            @click="onSubmit"
            >确 定</el-button
          >
        </div>
      </el-scrollbar>
    </div>
    <PersonSelect
      :visible.sync="personSelectVisible"
      width="70%"
      :selectedArr="selectedArr"
      :component="dataType"
      :multiple="false"
      @cancel="cancel"
      @confirm="selectConfirm"
    ></PersonSelect>
  </div>
</template>

<script>
import { applyCard, applicationList, getStockNum, getAuditerList } from "@/api";
import { checkPhoneValid } from "@/utils/validate";
import { getDateStr } from "@/utils/getNDate";

export default {
  components: {
    PersonSelect: () => import("@/components/PersonSelect"),
  },
  data() {
    var validateNumber = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写申请张数"));
      } else if (value == 0) {
        callback(new Error("申请张数不能为0"));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("收件人电话不能为空"));
      } else {
        if (checkPhoneValid(value)) {
          callback();
        } else {
          callback(new Error("请填写正确格式的联系电话"));
        }
      }
    };
    return {
      stockNum: 0,
      loading: false,
      form: {
        applyType: "",
        isTest: "",
        codeExpireTime: "",
        codeKey: "",
        cardType: "",
        applyReason: "",
        auditObj: null,
        cost: "",
        applyNum: "",
        // applyName: "",
        expireTime: "",
        auditAdminName: "",
        auditAdminId: "",
        department: "",
        list: [],
        receiverPhone: "",
        receiverName: "",
        receiverAddress: "",
      },
      rules: {
        applyType: [
          { required: true, message: "请选择职途卡类型", trigger: "change" },
        ],
        codeExpireTime: [
          { required: true, message: "请选择二维码有效期", trigger: "change" },
        ],
        codeKey: [
          {
            required: false,
            message: "请填写职途卡密码",
            trigger: "change",
          },
        ],
        isTest: [{ required: true, message: "职途卡用途", trigger: "change" }],
        cardChannel: [
          { required: true, message: "请选择职途卡渠道", trigger: "change" },
        ],
        applyNum: [
          { required: true, validator: validateNumber, trigger: "blur" },
        ],
        expireTime: [
          {
            type: "string",
            required: true,
            message: "请选择职途卡有效期",
            trigger: "change",
          },
        ],
        applyReason: [
          { required: true, message: "请填写申请理由", trigger: "change" },
        ],
        auditObj: [
          { required: true, message: "请选择审核人", trigger: "change" },
        ],
        department: [
          { required: true, message: "请选申请部门", trigger: "change" },
        ],
        cardType: [
          { required: true, message: "请选择项目应用方", trigger: "change" },
        ],
        auditAdminName: [
          { required: true, message: "请填写申请人名称", trigger: "change" },
        ],
        cost: [{ required: true, message: "请填写单价", trigger: "blur" }],
        receiverName: [
          { required: true, message: "请填写收件人名称", trigger: "blur" },
        ],
        receiverPhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        receiverAddress: [
          { required: true, message: "请填写收件地址", trigger: "blur" },
        ],
      },
      projectTypeOptions: [
        { label: "职途实体卡", value: 1 },
        { label: "职途电子卡", value: 2 },
        { label: "线上二维码", value: 3 },
      ],
      isTestOptions: [
        { label: "正式", value: 0 },
        { label: "测试", value: 1 },
      ],
      auditerList: [],
      appList: [],
      localAppList: [],
      showCardSource: false,
      showQrCodeExpireTime: false,
      personSelectVisible: false,
      selectedArr: [],
      dataType: "el-dialog",
      currentSelectApplyPersonInfo: {},
      flag: "",
    };
  },
  watch: {
    "form.applyType": {
      handler(val) {
        if (val == 1) {
          this.showCardSource = true;
        } else {
          this.showCardSource = false;
        }
        if (val == 3) {
          this.showQrCodeExpireTime = true;
        } else {
          this.showQrCodeExpireTime = false;
        }
      },
    },
    "form.isTest": {
      handler() {
        this.getStockNumFn();
      },
    },
  },
  created() {
    this.getDateStrFn();
    this.applicationListFn();
    this.getAuditerListFn();
    this.getStockNumFn();
  },
  methods: {
    getDateStrFn() {
      this.form.expireTime = getDateStr(365);
    },
    handleChangeCardType(val) {
      this.localAppList.forEach((item) => {
        if (item.appId == val[0]) {
          item.cardTypeList.forEach((_item) => {
            if (_item.cardType == val[1]) {
              this.form.list = _item.rightList;
            }
          });
        }
      });
    },
    getAuditerListFn() {
      getAuditerList().then((res) => {
        if (res.code == 200) {
          this.auditerList = res.data;
          if (this.auditerList.length > 0) {
            const temp = this.auditerList.find(
              (item) => item.auditAdminId == "228"
            );
            temp && (this.form.auditObj = temp);
          }
        }
      });
    },
    getStockNumFn() {
      const params = {
        applyType: this.form.applyType,
        isTest: this.form.isTest,
      };
      getStockNum(params).then((res) => {
        if (res.code == 200) {
          this.stockNum = res.data;
        }
      });
    },
    applicationListFn() {
      applicationList()
        .then((res) => {
          if (res.code == 200) {
            this.localAppList = res.data;
            const temp = [];
            res.data.forEach((item, index) => {
              temp.push({
                label: item.appName,
                value: item.appId,
              });
              const temp2 = [];
              if (item.cardTypeList) {
                item.cardTypeList.forEach((item2) => {
                  temp2.push({
                    label: item2.cardName,
                    value: item2.cardType,
                  });
                });
              }
              temp[index].children = temp2;
            });
            this.appList = temp;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleFocusInput() {
      this.personSelectVisible = true;
    },
    selectConfirm(e) {
      this.currentSelectApplyPersonInfo = e[0];
      this.form.auditAdminName = e[0].name;
      this.form.department = e[0].dept;
    },
    cancel() {
      this.personSelectVisible = false;
    },
    checkIfNum() {
      this.form.applyNum = this.form.applyNum.toString().replace(/\D/g, "");
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm("请再次确认申请的事项是否正确", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.loading = true;
            const params = {
              ...this.form,
              cardType: this.form.cardType[this.form.cardType.length - 1],
              codeExpireTime: this.form.codeExpireTime
                ? this.form.codeExpireTime + " 23:59:59"
                : "",
              expireTime: this.form.expireTime + " 23:59:59",
              applyAdminId: this.currentSelectApplyPersonInfo.id,
              applyAdminName: this.currentSelectApplyPersonInfo.name,
              department: this.currentSelectApplyPersonInfo.dept,
              auditAdminId: this.form.auditObj.auditAdminId,
              auditAdminName: this.form.auditObj.auditAdminName,
            };
            applyCard(params)
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success("已提交申请，请等待审核");
                  const keys = Object.keys(this.form);
                  keys.forEach((key) => {
                    if (key == "auditObj") {
                      this.form[key] = null;
                    } else if (key == "rights") {
                      this.form[key] = [];
                    } else {
                      this.form[key] = "";
                    }
                  });
                  this.showCardSource = false;
                  this.$nextTick(() => {
                    this.$refs.form.clearValidate();
                  });
                  this.$router.push("/cardManage/recordList");
                } else {
                  this.$message.error(res.status_desc);
                }
              })
              .catch((err) => {
                this.$message.error(err);
              })
              .finally(() => {
                this.loading = false;
              });
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.record-wrapper {
  width: 100%;
  height: calc(100vh - 54px);
  overflow-y: hidden;
  background: url("../../../assets/images/bigBg.png") no-repeat;
  background-position: center;
  background-size: 100% 100%;
  background-color: #fff;
  // margin-left: 24px;
  .container {
    height: 100%;
    margin: 0 24px 0 12px;
    background-color: #fff;
    border-radius: 8px 8px 0 0;
    .page-title {
      font-size: 22px;
      color: #222;
      font-weight: 600;
      padding: 18px 24px;
      border-bottom: 1px solid #f2f2f2;
    }
    .scrollbar {
      height: calc(100vh - 59px - 54px);
    }
    .form-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 auto;
      margin-top: 24px;
      width: 70%;
      .left-num {
        font-size: 14px;
        color: #f44716;
      }
      .form {
        width: 100%;
        .select {
          width: 100%;
        }
        .spe-select {
          width: 87%;
        }
        .flex {
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: $primary_color;
          font-size: 15px;
          .icon-container {
            display: flex;
            align-items: center;
            cursor: pointer;
            .self-icon {
              font-size: 18px;
              margin-right: 3px;
            }
          }
        }
        .checkbox {
          ::v-deep .el-form-item__content {
            display: flex;
          }
        }
        ::v-deep .el-form-item--small.el-form-item {
          margin-bottom: 32px;
        }
        ::v-deep .el-tag.el-tag--info {
          margin-right: 8px;
          color: #333;
        }
      }
      ::v-deep .el-form-item__label {
        padding: 0 4px 0 0;
      }
    }
  }
  .operation {
    padding: 15px 0;
    border-top: 1px solid #f2f2f2;
    display: flex;
    justify-content: center;
    .btn {
      width: 200px;
    }
  }
}
</style>
